package com.sc.friend.ui

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.core.view.marginTop
import androidx.databinding.DataBindingUtil
import androidx.core.widget.doOnTextChanged
import com.sc.friend.BaseActivity
import com.sc.friend.R
import com.sc.friend.databinding.ActivityLoginCodeBinding

class LoginCodeActivity : BaseActivity() {
    private lateinit var binding: ActivityLoginCodeBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login_code)

        setupOtpAutoAdvance()

        binding.etCode1.doOnTextChanged { _, _, _, _ -> checkAndNavigateIfComplete() }
        binding.etCode2.doOnTextChanged { _, _, _, _ -> checkAndNavigateIfComplete() }
        binding.etCode3.doOnTextChanged { _, _, _, _ -> checkAndNavigateIfComplete() }
        binding.etCode4.doOnTextChanged { _, _, _, _ -> checkAndNavigateIfComplete() }

        setClick()
    }

    //设置输入框的监听事件
    private fun setupOtpAutoAdvance() {
        binding.etCode1.doOnTextChanged { text, _, _, _ ->
            if (!text.isNullOrEmpty()) binding.etCode2.requestFocus()
        }
        binding.etCode2.doOnTextChanged { text, _, _, _ ->
            if (!text.isNullOrEmpty()) binding.etCode3.requestFocus()
        }
        binding.etCode3.doOnTextChanged { text, _, _, _ ->
            if (!text.isNullOrEmpty()) binding.etCode4.requestFocus()
        }
    }

    private fun setClick(){
        binding.imageBack.setOnClickListener{
            finish()
        }
    }

    private fun checkAndNavigateIfComplete() {
        val allFilled = listOf(
            binding.etCode1.text?.toString()?.trim(),
            binding.etCode2.text?.toString()?.trim(),
            binding.etCode3.text?.toString()?.trim(),
            binding.etCode4.text?.toString()?.trim(),
        ).all { !it.isNullOrEmpty() }

        if (allFilled) {
            val intent = Intent(this, PhotoActivity::class.java)
            startActivity(intent)
        }
    }
} 